package com.jereh.topnews.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jereh.topnews.R;
import com.jereh.topnews.activity.NewsDetailActivity;
import com.jereh.topnews.adapter.NewsListAdapter;
import com.jereh.topnews.api.NewsApi;
import com.jereh.topnews.callback.CallBack;
import com.jereh.topnews.db.ContentDao;
import com.jereh.topnews.entity.Channel;
import com.jereh.topnews.entity.Content;
import com.jereh.topnews.fragment.base.BaseFragment;
import com.jereh.topnews.util.HttpUtil;
import com.jereh.topnews.util.RequestUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/14.
 */
public class NewsItemFragment extends BaseFragment implements CallBack{

    private PullToRefreshListView pullListView;
    private ListView listView;
    private BaseAdapter adapter;
    private List<Content> list=new ArrayList<>();
    private Context ctx;
    private Channel channel;
    private ContentDao contentDao;
    private RequestUtil requestUtil;

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        menu.add(Menu.NONE, 0, 0, "是否删除该条新闻");
        menu.setHeaderTitle("删除新闻");
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if(getUserVisibleHint()==true) {
            //通过菜单项得到菜单信息
            AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
            //通过menuInfo的position属性获取Listview选中的那一行下标
//            Toast.makeText(ctx, "adapter context Position:" + menuInfo.position + "list size:" + list.size(), Toast.LENGTH_SHORT).show();
            Toast.makeText(ctx, "成功删除该条新闻，标题是："+list.get(menuInfo.position-1).getTitle(), Toast.LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.ctx=context;
        requestUtil=new RequestUtil(ctx,this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //获取数据
        channel=(Channel)getArguments().getSerializable("channel");
        //获取contentDao对象
        contentDao=new ContentDao(ctx);
        View view=inflater.inflate(R.layout.list_news_view,null);
        isPrepared=true;
        pullListView=(PullToRefreshListView)view.findViewById(R.id.pull);
        listView=pullListView.getRefreshableView();
        adapter=new NewsListAdapter(ctx,list);
        listView.setAdapter(adapter);
        pullListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                list.clear();
                onLazyLoad();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

            }
        });
        //列表设置点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(ctx, NewsDetailActivity.class);
                intent.putExtra("content",list.get(position-1));
                intent.putExtra("channel",channel);
                startActivity(intent);
            }
        });
        registerForContextMenu(listView);//长按删除新闻
        onLazyLoad();
        return view;
    }

    private void setData() {
        //获取api接口
        String api=NewsApi.getNewsListApi(channel,1);
        //获取数据
        String json= HttpUtil.getDataByApi(api);
        //通过数据解析对象
        list.addAll(HttpUtil.getContentByJson(json));
    }

    @Override
    protected void onLazyLoad() {
        if(isPrepared&&isVisible){
            //加载数据
//            updateData();
            requestUtil.setDataByUrl(NewsApi.getNewsListApi(channel, 1));
        }
    }

    @Override
    public void callback(String json) {
//        Log.e("jereh",json);
        try {
            JSONObject object = JSON.parseObject(json);
            JSONObject body = (JSONObject) object.get("showapi_res_body");
            JSONObject pagebean = (JSONObject)body.get("pagebean");
            JSONArray contentlist=pagebean.getJSONArray("contentlist");
            list.addAll(JSON.parseArray(contentlist.toJSONString(), Content.class));
            //本地数据缓存
            contentDao.addAll(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        adapter.notifyDataSetChanged();
        pullListView.onRefreshComplete();
    }

    @Override
    public void errorCallback() {
        list.addAll(contentDao.findContentByChannel(channel));
        adapter.notifyDataSetChanged();
        Toast.makeText(ctx, "请联网后更新最新数据", Toast.LENGTH_SHORT).show();
        pullListView.onRefreshComplete();
    }
}
